import type { ComputedRef, Ref } from 'vue';
import { toValue } from 'vue';
import { REG_IPV4, REG_IPV6, REG_LENGTH, REG_MAC, REG_NUMBER } from '@/constants/reg';

/** 获取长度规则 */
export function createLengthRule(end: number): App.Global.FormRule {
  return {
    pattern: REG_LENGTH(0, end),
    message: `长度不超过${end}个字符`,
    trigger: 'blur'
  };
}

/** 获取长度范围 */
export function createLengthRangeRule(start: number, end: number): App.Global.FormRule {
  return {
    pattern: REG_LENGTH(start, end),
    message: `长度在${start}~${end}个字符之间`,
    trigger: 'blur'
  };
}

/** 条款 */
export function createAgreePolicyRule() {
  const agreePolicyRule: App.Global.FormRule[] = [
    {
      asyncValidator: (rule, value) => {
        if (value === 'N') {
          return Promise.reject(rule.message);
        }
        return Promise.resolve();
      },
      message: '请同意隐私政策和条款',
      trigger: 'change'
    }
  ];
  return agreePolicyRule;
}

/** 确认密码规则 */
export function createConfirmPwdRule(pwd: string | Ref<string> | ComputedRef<string>) {
  const confirmPwdRule: App.Global.FormRule[] = [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    {
      asyncValidator: (rule, value) => {
        if (value.trim() !== '' && value !== toValue(pwd)) {
          return Promise.reject(rule.message);
        }
        return Promise.resolve();
      },
      message: '两次输入密码不一致',
      trigger: 'blur'
    }
  ];
  return confirmPwdRule;
}

/**
 * Ip地址规则
 *
 * @param type ip类型，默认ipv4
 * @param exceptStartEnd ip4，是否排除起始和结束地址（去掉0和255），默认false
 * @returns
 */
export function createIpRule({
  type = 'ipv4',
  exceptStartEnd = false
}: { type?: CommonType.IpType; exceptStartEnd?: boolean } = {}) {
  const reg = type === 'ipv4' ? REG_IPV4 : REG_IPV6;
  const ipRule: App.Global.FormRule = {
    asyncValidator: (rule, value) => {
      if ([null, undefined, ''].includes(value)) {
        return Promise.resolve();
      }
      if (!reg.test(value)) {
        return Promise.reject(rule.message);
      }
      /** 排除起始和结束地址 */
      if (type === 'ipv4' && exceptStartEnd && ['0', '255'].includes(value.split('.').pop())) {
        return Promise.reject(rule.message);
      }
      return Promise.resolve();
    },
    message: 'IP地址格式错误，请检查',
    trigger: 'blur'
  };

  return ipRule;
}

/** ipv4 或 ipv6 */
export function createIpv4OrIpv6Rule() {
  const ipRule: App.Global.FormRule = {
    asyncValidator: (rule, value) => {
      if ([null, undefined, ''].includes(value)) {
        return Promise.resolve();
      }
      if (REG_IPV4.test(value) || REG_IPV6.test(value)) {
        return Promise.resolve();
      }
      return Promise.reject(rule.message);
    },
    message: 'IP地址格式错误，请检查',
    trigger: 'blur'
  };

  return ipRule;
}

/**
 * 数字范围规则
 *
 * @param min 最小值
 * @param max 最大值
 */
export function createNumberRange(min: number, max: number) {
  const numberRange: App.Global.FormRule = {
    asyncValidator: (_rule, value) => {
      if ([null, undefined, ''].includes(value)) {
        return Promise.resolve();
      }
      if (!REG_NUMBER.test(value)) {
        return Promise.reject(new Error('请输入数字'));
      }
      if (value > max || value < min) {
        return Promise.reject(new Error(`请输入${min}-${max}之间的整数`));
      }
      return Promise.resolve();
    },
    type: 'number',
    trigger: 'blur'
  };

  return numberRange;
}

/** 校验 MAC 地址 */
export function createMACRule() {
  const macRule: App.Global.FormRule = {
    asyncValidator: (rule, value) => {
      if ([null, undefined, ''].includes(value)) {
        return Promise.resolve();
      }
      if (REG_MAC.test(value)) {
        return Promise.resolve();
      }
      return Promise.reject(rule.message);
    },
    message: 'MAC地址格式错误，请检查',
    trigger: 'blur'
  };

  return macRule;
}
